package com.tgy.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/***
 * @ClassName: Performance
 * @Description: 反射性能问题
 * @Auther: 送一一块二向箔
 * @Date: 20:16 2021/12/1
 * @version : V1.0
 */
public class Performance {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
        test1();
        test2();
        test3();
    }
    //普通方式
    public static void test1(){
        User user = new User();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user.getAge();
        }
        long endTime  = System.currentTimeMillis();
        System.out.println("普通方法调用时间"+(endTime-startTime)+"ms");
    }
    //反射方式调用
    //普通方式
    public static void test2() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<User> c2 = User.class;
        User user2 = c2.newInstance();
        Method getAge = c2.getDeclaredMethod("getAge",null);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getAge.invoke(user2,null);
        }
        long endTime  = System.currentTimeMillis();
        System.out.println("反射调用时间"+(endTime-startTime)+"ms");
    }

    //反射方式调用，打开setAccessible
    public static void test3() throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
        Class<User> c3 = User.class;
        User user2 = c3.newInstance();
        Method getAge = c3.getDeclaredMethod("getAge",null);
        getAge.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getAge.invoke(user2,null);
        }
        long endTime  = System.currentTimeMillis();
        System.out.println("打开通过后反射调用时间"+(endTime-startTime)+"ms");
    }



}
